import pandas as pd

# 定义 LSR 计算函数
def calculate_lsr(controllers, short_debt, long_debt):
    state_owned_types = ['1100', '2000', '2100', '2120']
    if controllers[0] in state_owned_types:
        lsr = short_debt + 0.5 * long_debt
    else:
        lsr = short_debt + 0.4 * long_debt
    return lsr

# 读取 Excel 文件
file_path = r'C:\Users\Lenovo\PycharmProjects\pythonProject1\a2.xlsx'
try:
    data = pd.read_excel(file_path)
except FileNotFoundError:
    print(f"错误：文件不存在。请确认文件路径是否正确。")
except Exception as e:
    print(f"读取 Excel 文件时发生错误：{e}")

# 应用 LSR 函数计算每个企业的 LSR 值
try:
    data['LSR'] = data.apply(lambda row: calculate_lsr([str(row['所有权'])], row['短期负债'], row['长期负债合计']), axis=1)
except Exception as e:
    print(f"在计算 LSR 时发生错误: {e}")

# 保存更新后的 DataFrame 回到原来的 Excel 文件
try:
    data.to_excel(file_path, index=False)
    print("LSR 值已成功追加并保存到文件中。")
except Exception as e:
    print(f"保存文件时发生错误: {e}")